package com.telenav.data.dao;

import com.telenav.persistent.AbstractStore;
import com.telenav.persistent.PersistentManager;

public class AccountDao {

    private AbstractStore accountStore;
    
   private static final int ACCOUNT_STATUS_INDEX = 10000;
   
   private static final int ACCOUNT_NAME_INDEX = 10001;
   
   private static final int ACCOUNT_PWD_INDEX = 10002;
   
   private static final int ACCOUNT_GCM_IS_REGISTER = 10003;
   
   public static final int ACCOUNT_STATUS_UNKNOWN = -1;
   
   public static final int ACCOUNT_STATUS_NORMAL = 0;
   
   public static final int ACCOUNT_STATUS_EXCEPTION = 1;
	
	private static class SingletonHolder 
    {
        public static final AccountDao INSTANCE = new AccountDao();
    }

    public static AccountDao getInstance() 
    {
        return SingletonHolder.INSTANCE;
    }
    
    private AccountDao()
    {
    	accountStore = PersistentManager.getInstance().createStore(PersistentManager.DATABASE, "user_data");
    	accountStore.load();
    }
    
    
    public boolean isLogin()
    {
    	if(this.getAccountName() != null && this.getAccountPWD() != null)
    	{
    		return true;
    	}
    	return false;
    }
    
    public String getAccountName()
    {
        if (this.accountStore != null)
        {
            byte[] accountData = this.accountStore.get(ACCOUNT_NAME_INDEX);
            if (accountData != null)
            {
                return new String(accountData);
            }
        }
        return null;
    }
    
    public String getAccountPWD()
    {
        if (this.accountStore != null)
        {
            byte[] accountData = this.accountStore.get(ACCOUNT_PWD_INDEX);
            if (accountData != null)
            {
                return new String(accountData);
            }
        }
        return null;
    }
    
    
    public void setAccount(String username, String password)
    {
        if (username ==null || password ==null)
            return;
        
        if(this.accountStore != null)
        {
            this.accountStore.put(ACCOUNT_NAME_INDEX, username.getBytes());
            this.accountStore.put(ACCOUNT_PWD_INDEX, password.getBytes());
        }
    }
    
    public void clearAccount()
    {
    	this.accountStore.clear();
    }
    
    public void setIsRegister(boolean isRegister)
    {
    	this.accountStore.put(ACCOUNT_GCM_IS_REGISTER, isRegister ? "1".getBytes() : "0".getBytes());
    }
    
    public boolean isRegister()
    {
        if (this.accountStore != null)
        {
            byte[] isRegisterData = this.accountStore.get(ACCOUNT_GCM_IS_REGISTER);
            if (isRegisterData != null)
            {
                String value = new String(isRegisterData);
                if(value.equals("1"))
                	return true;
            }
        }
        return false;
    }
}
